package com.hiyee.admin.controller;

import com.hiyee.admin.service.AdminUserService;
import com.hiyee.api.BaseController;
import com.hiyee.api.controller.admin.AdminUserControllerApi;
import com.hiyee.grace.result.ResponseJsonResult;
import com.hiyee.grace.result.ResponseStatusEnum;
import com.hiyee.pojo.AdminUser;
import com.hiyee.pojo.bo.AdminUserLoginBO;
import com.hiyee.pojo.bo.UpdateAdminUserBO;
import com.hiyee.utils.PagedGridResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.UUID;

@RestController
public class AdminUserController extends BaseController implements AdminUserControllerApi {

    @Autowired
    AdminUserService adminUserService;
    @Autowired
    RestTemplate restTemplate;

    @Override
    public Object login(AdminUserLoginBO adminUserLoginBO, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) {

        // 参数校验
        if(bindingResult.hasErrors()) {
            return ResponseJsonResult.errorMap(this.getErrors(bindingResult));
        }

        // 查询用户
        AdminUser adminUser = adminUserService.getByUsername(adminUserLoginBO.getUsername());
        if(adminUser == null) {
            return ResponseJsonResult.error(ResponseStatusEnum.ADMIN_USER_NOT_FOUND);
        }

        // 校验密码
        boolean checkPw = BCrypt.checkpw(adminUserLoginBO.getPassword(), adminUser.getPassword());
        if(!checkPw) {
            return ResponseJsonResult.error(ResponseStatusEnum.ADMIN_USER_PW_ERROR);
        }
        // 写入缓存
        doLoginSetting(adminUser, request, response);

        // 调用 files 服务
        ResponseEntity<ResponseJsonResult> responseEntity = restTemplate.getForEntity("http://localhost:8004/file/getFile", ResponseJsonResult.class);
        ResponseJsonResult bodyResult = responseEntity.getBody();
        System.out.println("[文件服务] 返回值：" + bodyResult.getData().toString());
        return ResponseJsonResult.success();
    }

    private void doLoginSetting(AdminUser adminUser, HttpServletRequest request, HttpServletResponse response)
    {
        // 生成token
        String token = UUID.randomUUID().toString();
        redisOperator.set(REDIS_KEY_ADMIN_TOKEN + adminUser.getId(), token, 12 * 60 * 60);

        // 注入 cookie
        setCookie(request, response, "atoken", token, COOKIE_LIFE_TIME);
        setCookie(request, response, "aid", adminUser.getId(), COOKIE_LIFE_TIME);
        setCookie(request, response, "aname", adminUser.getAdminName(), COOKIE_LIFE_TIME);
    }

    @Override
    public Object checkUnique(String username) {

        AdminUser adminUser = adminUserService.getByUsername(username);
        if(adminUser != null) {
            return ResponseJsonResult.error(ResponseStatusEnum.ADMIN_USER_NAME_EXIST);
        }
        return ResponseJsonResult.success();
    }

    @Override
    public Object addNewAdmin(@Valid UpdateAdminUserBO updateAdminUserBO,
                              BindingResult bindingResult,
                              HttpServletRequest request,
                              HttpServletResponse response) {
        // 参数校验
        if(bindingResult.hasErrors()) {
            return  ResponseJsonResult.errorMap(this.getErrors(bindingResult));
        }

        // 非人脸入库
        if(StringUtils.isBlank(updateAdminUserBO.getImg64())) {
            if(!updateAdminUserBO.getPassword().equals(updateAdminUserBO.getConfirmPassword())) {
                return ResponseJsonResult.error(ResponseStatusEnum.ADMIN_USER_PW_CONFIRM_FAIL);
            }
        }
        // 校验账户唯一
        AdminUser check = adminUserService.getByUsername(updateAdminUserBO.getUsername());
        if(check != null) {
            return ResponseJsonResult.error(ResponseStatusEnum.ADMIN_USER_NAME_EXIST);
        }
        // 添加管理员
        adminUserService.createAdminUser(updateAdminUserBO);
        return ResponseJsonResult.success();
    }

    @Override
    public Object getAdminList(Integer page, Integer pageSize) {
        if(page == null) {
            page = DEFAULT_PAGE;
        }
        if(pageSize == null) {
            pageSize = DEFAULT_PAGE_SIZE;
        }

        PagedGridResult result = adminUserService.getAdminList(page, pageSize);
        return ResponseJsonResult.success(result);
    }

    @Override
    public Object logout(String adminId, HttpServletRequest request, HttpServletResponse response) {

        // 删除 token
        redisOperator.del(REDIS_KEY_ADMIN_TOKEN + adminId);
        // 删除 cookie
        deleteCookie(request, response, "atoken");
        deleteCookie(request, response, "aid");
        deleteCookie(request, response, "aname");

        return ResponseJsonResult.success();
    }
}
